package com.yunju.xuexin.xuexincrawler.utils;

import java.io.IOException;
import java.util.List;

import okhttp3.Headers;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * OKHttp Utils
 * 
 * @author liuzhijun
 *
 */
public class RequestUtils {

	/**
	 * 执行post方法
	 * 
	 * @param url
	 * @param requestBody
	 * @param forData
	 * @param headers
	 * @return
	 * @throws IOException
	 */
	public Response doPost(String url, RequestBody requestBody,
			List<String> formData, Headers headers) throws IOException {
		OkHttpClient client = new OkHttpClient();
		return doPost(client, url, requestBody, formData, headers);
	}

	/**
	 * 执行post方法，用户自定义client
	 * 
	 * @param client
	 * @param url
	 * @param requestBody
	 * @param forData
	 * @param headers
	 * @return
	 * @throws IOException
	 */
	public Response doPost(OkHttpClient client, String url,
			RequestBody requestBody, List<String> formData, Headers headers)
			throws IOException {
		Request request = new Request.Builder().headers(headers).url(url)
				.post(requestBody).build();
		Response resp = client.newCall(request).execute();
		return resp;
	}

	/**
	 * 执行Get方法
	 * 
	 * @param url
	 * @return
	 * @throws IOException
	 */
	public Response doGet(String url, Headers headers) throws IOException {
		OkHttpClient client = new OkHttpClient();
		return doGet(client, url, headers);
	}

	/**
	 * 执行Get方法
	 * 
	 * @param client
	 * @param url
	 * @param headers
	 * @return
	 * @throws IOException
	 */
	public Response doGet(OkHttpClient client, String url, Headers headers)
			throws IOException {
		Request request = new Request.Builder().headers(headers).url(url)
				.build();
		Response resp = client.newCall(request).execute();
		return resp;
	}
}
